//计算右侧小于等于当前元素的个数--归并排序

class Solution {
public:
    vector<int> ret;
    vector<int> index;
    int tmpNums[500001];
    int tmpIndex[500001];
    vector<int> countSmaller(vector<int>& nums) {
        int n = nums.size();
        ret.resize(n);
        index.resize(n);
        for(int i = 0;i < n; i++)
        {
            index[i] = i;
        }
        MergeSort(nums, 0, n - 1);
        return ret;
    }
    void MergeSort(vector<int>& nums, int left, int right)
    {
        if(left >= right) return;
        int mid = left + (right - left)/ 2;
        //[left, mid] [mid + 1, right]
        MergeSort(nums, left, mid);
        MergeSort(nums, mid + 1, right);
        int cur1 = left, cur2 = mid + 1, i = 0;
        while(cur1 <= mid && cur2 <= right)
        {
            if(nums[cur1] > nums[cur2])
            {
                tmpNums[i] = nums[cur1];
                ret[index[cur1]] += right - cur2 + 1;
                tmpIndex[i++] = index[cur1++];
            }
            else
            {
                tmpNums[i] = nums[cur2];
                tmpIndex[i++] = index[cur2++];
            }
        }
        while(cur1 <= mid)
        {
            tmpNums[i] = nums[cur1];
            tmpIndex[i++] = index[cur1++];
        }
        while(cur2 <= right)
        {
            tmpNums[i] = nums[cur2];
            tmpIndex[i++] = index[cur2++];
        }
        for(int j = left; j <= right; j++)
        {
            nums[j] = tmpNums[j - left];
            index[j] = tmpIndex[j - left];
        }
    }
};